package main

import (
	"fmt"
	"image"
	"path/filepath"

	"demserver/src/elevation"
)

func main() {
	// Use the actual GeoTIFF file
	filename := "./demdata/ClipResult.tif"

	// Get absolute path to the file
	absPath, err := filepath.Abs(filename)
	if err != nil {
		fmt.Printf("Failed to get absolute path: %v\n", err)
		return
	}

	fmt.Printf("Loading GeoTIFF file: %s\n", absPath)
	geoTiff, err := elevation.LoadGeoTIFF(absPath)
	if err != nil {
		fmt.Printf("Failed to load GeoTIFF: %v\n", err)
		return
	}
	fmt.Println("GeoTIFF loaded successfully")
	fmt.Printf("Image type: %T\n", geoTiff.Image)

	// Analyze the relationship between pixel values and expected elevations
	// We'll use a few test points to understand the data better
	testData := []struct {
		lat      float64
		lon      float64
		expected float64
	}{
		{31.02659757575758, 103.54607363636364, 780.2126995110525},
		{31.037039, 103.572044, 806.0841527110774},
		{31.0304264, 103.5912788, 773.8375500820072},
		{31.0013281, 103.607449, 727.5249991936447},
		{30.99902, 103.61049, 731.2953275545822},
	}

	fmt.Println("\nAnalyzing pixel values and expected elevations:")
	fmt.Printf("%-15s %-15s %-15s %-15s %-15s %-15s\n", "Lat", "Lon", "Expected", "Pixel Value", "Difference", "Ratio")

	for _, data := range testData {
		x, y, err := geoTiff.LatLonToPixel(data.lat, data.lon)
		if err != nil {
			fmt.Printf("Failed to convert coordinates (%f, %f): %v\n", data.lat, data.lon, err)
			continue
		}

		// Check if coordinates are within bounds
		if x < 0 || y < 0 || x >= float64(geoTiff.Width) || y >= float64(geoTiff.Height) {
			fmt.Printf("%-15.6f %-15.6f %-15.6f %-15s %-15s %-15s\n", data.lat, data.lon, data.expected, "Out of bounds", "N/A", "N/A")
			continue
		}

		// Get the raw pixel value directly
		xInt := int(x)
		yInt := int(y)
		pixelValue := getRawPixelValue(geoTiff, xInt, yInt)

		// Calculate difference and ratio
		difference := pixelValue - data.expected
		ratio := 0.0
		if data.expected != 0 {
			ratio = pixelValue / data.expected
		}

		fmt.Printf("%-15.6f %-15.6f %-15.6f %-15.0f %-15.6f %-15.6f\n", data.lat, data.lon, data.expected, pixelValue, difference, ratio)
	}

	// Let's also check a range of pixel values to understand the data distribution
	fmt.Println("\nAnalyzing pixel value distribution:")
	if grayImg, ok := geoTiff.Image.(*image.Gray16); ok {
		fmt.Printf("%-10s %-10s %-10s %-10s\n", "X", "Y", "Raw Value", "As Float")
		// Check a grid of pixels
		for y := 5000; y < 5010; y++ {
			for x := 10000; x < 10010; x++ {
				if x < geoTiff.Width && y < geoTiff.Height {
					value := grayImg.Gray16At(x, y)
					fmt.Printf("%-10d %-10d %-10d %-10.2f\n", x, y, value.Y, float64(value.Y))
				}
			}
		}
	}
}

func getRawPixelValue(geoTiff *elevation.GeoTIFF, x, y int) float64 {
	// Get the raw pixel value without any interpolation
	grayImg, ok := geoTiff.Image.(*image.Gray16)
	if ok {
		value := grayImg.Gray16At(x, y)
		return float64(value.Y)
	}
	return 0
}
